package com.homeassistant.function;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import android.os.Environment;

public class Function {
	
	/**
	 * 检查是否存在SD卡
	 * @return
	 */
	public boolean CheckExistSD(){
		boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
		return sdCardExist;
	}
	
	/**
	 * 读取本地文件的数据流
	 * @param filePath 本地文件地址
	 * @return
	 * @throws IOException
	 */
	public InputStream readFile(String filePath) throws IOException{
		File mFile = new File(filePath);
		if(mFile.exists() && mFile.canRead()){
			FileInputStream mFileInputStream = new FileInputStream(mFile);
			return mFileInputStream;
		}else{
			return null;
		}
	}
	
	/**
	 * 读取远程服务器上的数据流
	 * @param uri 远程服务的Http地址
	 * @return
	 * @throws IOException
	 */
	public InputStream readFile(URI uri) throws IOException{
		String urlPath = uri.getPath();
		URL url = new URL(urlPath);
		HttpURLConnection mHttpURLConnection = (HttpURLConnection)url.openConnection();
		return mHttpURLConnection.getInputStream();
	}
	
	/**
	 * 对针对文件进行追加写入操作
	 * @param filePath 文件路径
	 * @param writeString 追加的内容
	 * @throws IOException 
	 */
	public void writeFile(String filePath, String writeString) throws IOException{
		File mFile = new File(filePath);
		if(!mFile.exists()){
			CreateDir(filePath);
		}
		if(mFile.canWrite()){
			FileOutputStream mFileOutputStream = new FileOutputStream(mFile, true);
			byte[] buffer = writeString.getBytes();
			mFileOutputStream.write(buffer);
			mFileOutputStream.close();
		}
	}
	
	/**
	 * 根据文件路径检查并创建文件夹
	 * @param filePath 文件路径
	 * @throws IOException 
	 */
	public void CreateDir(String filePath) throws IOException{
		if(!CheckExistSD())
			return;
		filePath = filePath.replace("\\", "/");
		int index = filePath.lastIndexOf("/");
		String tempStr = filePath.substring(0, index);
		File mFile = new File(tempStr);
		if(!mFile.exists())
			mFile.mkdirs();
		mFile = new File(filePath);
		if(!mFile.exists())
			mFile.createNewFile();
	}
}
